using System;
using SharpObjects.Instantiation.Services;
using SharpObjects.Interfaces;
using SharpObjects.Configuration;
using SharpObjects.Configuration.ConfigurationProviders;
using System.Xml;

namespace SharpObjects.Logging.LogTargets
{
	public class LogTargetProxy : IXmlInitializable, ILogTarget
	{
	    protected bool isEnabled = true;
		public ILogTarget Target { get; set;}
		public IOriginFilter OriginFilter { get; set; }

		public LogTargetProxy()
		{
			Target = null;
			OriginFilter = null;
		}

		public LogTargetProxy(ILogTarget target, IOriginFilter filter)
		{
			Target = target;
			OriginFilter = filter;
		}

        #region IInitializable Members

        public void Initialize(XmlElement initializationElement)
        {
            IConfigurationProvider init = new XmlConfigurationProvider(initializationElement);
            //this.Target = init.GetObject<ILogTarget>("self::*");
            this.Id = init.GetString("@id");

            this.Target = ServiceFactory.Instance.GetService<ILogTarget>(this.Id);

            this.isEnabled = init.GetBoolean("is_enabled", init.GetBoolean("@is_enabled", true));
            this.OriginFilter = init.GetObject<IOriginFilter>("origin_filter", new OriginFilter());

            this.IsInitialized = true;
        }

        public bool IsInitialized { get; set; }


        #endregion

        #region ILogTarget Members

        public string Id { get; set; }

        public ILogFormatter Formatter { get; set; }

        public void Write(ILogEntry logEntry)
        {
            if (this.isEnabled)
            {
                if (this.OriginFilter.Pass(logEntry.Origin))
                {
                    this.Target.Write(logEntry);
                }
            }
        }

        public void Release()
        {
            this.Target.Release();
        }

        #endregion
    }
}
